<?php
class ModelLocalisationLocalisation extends Model
{
    public function getLanguageCode()
    {
        $lang_code='en';
        foreach(explode(',', $this->request->server['HTTP_ACCEPT_LANGUAGE']) as $code){
            if(is_string($code) && strlen($code)>1){
                if($code=='ru-ru') $code='ru';
                $lang_code=$code;
                break;
            }
        }

        return $lang_code;
    }

    public function getCountryCode()
    {

        if(isset($this->session->data['countryCode']) && $this->getTimeOut()) return $this->session->data['countryCode'];

        //$ip=$this->request->server['REMOTE_ADDR'];
        $ip='83.170.205.154';
        $countryCode='US';

        $this->load->model('localisation/ipAddressesModel');
        $ranges=$this->model_localisation_ipAddressesModel->getAll();

        foreach($ranges as $range){
            if($country=$this->checkAddress($ip, $range)){
                $countryCode=$country->code2;
                break;
            }
        }

        return $this->session->data['countryCode']=$countryCode;
    }

    public function getCurrencyCode()
    {
        $countryCode=$this->getCountryCode();
        $currency='USD';

        switch($countryCode){
            case 'RU';
                $currency='RUB';
                break;
            case 'DE';
                $currency='EUR';
                break;
            case 'UA';
                $currency='UAH';
                break;
        }

        return $currency;
    }

    protected function checkAddress($ip, $range){
        $ipArr=explode('.', $ip);
        $country=null;

        $result=false;
        foreach($range->range as $rang){
            if($rang){
                $minArr=explode('.', $rang[0]);
                $maxArr=explode('.', $rang[1]);

                $result=true;
                foreach($ipArr as $num=>$val){
                    if($val<$minArr[$num] || $val>$maxArr[$num]){
                        $result=false;
                        break;
                    }
                }
            }

            if($result){
                $this->load->model('localisation/countryModel');
                $country=$this->model_localisation_countryModel->findByPk($range->countryId);
                break;
            }
        }

        return $country;
    }

    protected function getTimeOut()
    {
        if(!isset($this->session->data['session_timeout'])){
            $this->session->data['session_timeout']=time();
            return false;
        }

        if((time()-$this->session->data['session_timeout'])<=$this->config->get('config_session_timeout')){
            $result=true;
        }else{
            $result=false;
            $this->session->data['session_timeout']=time();
        }

        return $result;
    }
}